<?php

    namespace Admin\Controller;

    use Common\Controller\AdminbaseController;

    class AdminCardController extends AdminbaseController {

        protected $m_logistics;
        protected $m_card;
        protected $m_card_sale;
        protected $m_recharge;
        protected $m_refund;

        function _initialize() {
            parent::_initialize();
            $this->m_logistics= D("Admin/Logistics");
            $this->m_card= D("Admin/Card");
            $this->m_card_sale = D("Sale/CardSale");
            $this->m_recharge = D("Admin/Recharge");
            $this->m_refund = D("Admin/Refund");
        }

        /**
         * 卡片列表
         */
        public function index(){
            $s_rid = I("request.s_rid");
            $this->assign("s_rid",$s_rid);
            $where = array();
            if(!empty($s_rid)){
                $where['c.lid'] =$s_rid;
            }
            $s_card_number = I("request.s_card_number");
            $this->assign("s_card_number",$s_card_number);
            if(!empty($s_card_number)){
                $where['c.number'] = array("like","%".$s_card_number."%");
            }

            $s_active = I("request.s_active");
            $this->assign("s_active",$s_active);
            if(!empty($s_active)){
                $s_active = $s_active == -1?0:$s_active;
                $where['c.is_active'] = $s_active;
            }

            $s_status = I("request.s_status");
            $this->assign("s_status",$s_status);
            if(!empty($s_status)){
                $where['c.status'] = $s_status;
            }

            $count=$this->m_card->alias("c")->where($where)->count();
            $page = $this->page($count, 15);

            if(!empty(I('s_download'))) {
                $export_list = $this->m_card->get_list($where,"c.status ASC,c.number DESC",0, $count);
                if (I('s_download') == 1) {
                    $export_title = array(
                        'number' => '卡号',
                        'is_active' => '是否激活',
                        'vip_name' => '用户名称',
                        'vip_phone' => '绑定手机号',
                        'vip_plate_number' => '绑定车牌号',
                        'logistics_name' => '所属机构',
                        'balance' => '可用余额',
                        'use_point' => '可用积分',
                        'point' => '总积分',
                        'active_price' => '卡费',
                        'status' => '状态',
                    );
                    foreach ($export_list AS &$item) {
                        $item['is_active'] = $item['is_active'] == 1 ? '已激活' : '未激活';
                        $item['status'] = $item['status'] == 1 ? '正常' : '已注销';
                    }
                    $excel = new \Common\Lib\excel();
                    $excel->export_data('卡记录列表', $export_title, $export_list);
                    exit;
                }
            }


            $list = $this->m_card->get_list($where,"c.status ASC,c.number DESC",$page->firstRow, $page->listRows);
            $logistics_list = $this->m_logistics->get_list();



            $allow_delete = false;
            if (session('ADMIN_ID') == '10') {
                $allow_delete = true;
            }
                
            $this->assign("allow_delete",$allow_delete);
            $this->assign("logistics_list",$logistics_list);
            $this->assign("page", $page->show('Admin'));
            $this->assign("list",$list);
            $this->display();
        }

        /**
         *  卡片金额记录
         */
        public function price_detail(){
            $list = array();
            $time_arr = array();
            $id = I("id",0,'intval');   //卡id
            if(empty($id)){
                $this->error("参数有误！");
            }
            $card = $this->m_card->where(array("id"=>$id))->find();
            if(empty($card)){
                $this->error("卡号不存在！");
            }
            //销售记录
            $sale_list = $this->m_card_sale->field("number,price,create_time,plus_price AS after_balance")->where(array("card_number"=>$card["number"]))->order("create_time")->select();
            $sale_price = 0;
            foreach($sale_list AS &$sitem){
                $sale_price = $sale_price+$sitem["price"];
                $sitem["price"] = -$sitem["price"];
                $sitem["remark"] = "卡消费";
                $time_arr[]  = $sitem["create_time"];
            }
            $list = $sale_list;
            //充值记录
            $recharge_list = $this->m_recharge->field("number,price,create_time,after_balance")->where(array("rid"=>$card["id"],"model"=>2))->order("create_time")->select();
            $recharge_price = 0;
            foreach($recharge_list AS &$ritem){
                $recharge_price = $recharge_price+$ritem["price"];
                $ritem["remark"] = "卡充值";
                $time_arr[]  = $ritem["create_time"];
            }
            $list = array_merge($list,$recharge_list);
            //退款记录
            $refund_list = $this->m_refund->field("number,price,create_time,after_balance")->where(array("rid"=>$card["id"],"model"=>2))->order("create_time")->select();
            $refund_price = 0;
            foreach($refund_list AS &$ritem2){
                $refund_price = $refund_price+$ritem2["price"];
                $ritem2["price"] = -$ritem2["price"];
                $sitem["remark"] = "卡退款";
                $time_arr[]  = $ritem2["create_time"];
            }
            $list = array_merge($list,$refund_list);
            array_multisort($time_arr, SORT_DESC, $list);


            if (I('s_download') == 1) {
                $export_title = array(
                    'number' => '账单号',
                    'price' => '金额',
                    'after_balance' => '操作后余额',
                    'remark' => '类型',
                    'create_time' => '操作时间',
                );
                $excel = new \Common\Lib\excel();
                $excel->export_data('卡号：'.$card["number"]."账单", $export_title, $list);
                exit;
            }


            $this->assign("card",$card);
            $this->assign("sale_price",$sale_price);
            $this->assign("recharge_price",$recharge_price);
            $this->assign("refund_price",$refund_price);
            $this->assign("list",$list);
            $this->display();
        }

        /**
         * 一级、二级物流发卡
         */
        public function send(){
            $id = I("get.id",0,'intval');
            $this->assign('id',$id);

            $manager_id = get_logistics_id();
            $manager_id = $manager_id?$manager_id:0;
            $this->assign('manager_id',$manager_id);

            $logistics_list = $this->m_logistics->get_list(array('manager_id'=>$manager_id));

            $this->assign("logistics_list",$logistics_list);

            if ($manager_id) {
                $this->display('send_sub');
            }else{
                $this->display();
            }
        }

        /**
         * 一级、二级物流发卡
         */
        public function send_sub(){
            $id = I("get.id",0,'intval');
            $this->assign('id',$id);

            $manager_id = get_logistics_id();
            $manager_id = $manager_id?$manager_id:0;
            $this->assign('manager_id',$manager_id);

            $logistics_list = $this->m_logistics->get_list(array('manager_id'=>$manager_id));

            $this->assign("logistics_list",$logistics_list);

            $this->display('send_sub');
        }

        /**
         * 代充物流公司发卡
         */
        public function send_vip_sub(){
            $id = I("get.id",0,'intval');
            $this->assign('id',$id);

            $manager_id = get_logistics_id();
            $manager_id = $manager_id?$manager_id:0;
            $this->assign('manager_id',$manager_id);

            $logistics_data = $this->m_logistics->get_data_one(array('id'=>$id));

            $this->assign("logistics_data",$logistics_data);

            $this->display('send_vip_sub');
        }


        /**
         * 无限制转卡-带余额操作
         */
        public function trans_card(){
            $id = I("get.id",0,'intval');
            $this->assign("card_number_list",I('card_number_list'));

            $this->assign('id',$id);

            $manager_id = get_logistics_id();
            $manager_id = $manager_id?$manager_id:0;
            $this->assign('manager_id',$manager_id);

            $logistics_list = $this->m_logistics->get_list(array('manager_id'=>$manager_id));

            $this->assign("logistics_list",$logistics_list);

            if ($manager_id) {
                $this->display('send_sub');
            }else{
                $this->display();
            }
        }


        /**
         * 发卡提交
         */
        public function trans_card_post(){

            $lid = I("post.lid");

            $logistics = $this->m_logistics->where(array("id"=>$lid))->find();
            if(empty($logistics)){
                $this->error("物流公司不存在！");
            }

            $plid = 1;
            $twhere = array("manager_id"=>$plid);
            $child_ids = $this->m_logistics->where($twhere)->getField('id');
            $child_ids = explode(',', $child_ids);
            $child_ids[] = $plid;


            $card_number_list = I("post.card_number_list");
            if (!empty($card_number_list)) {
                $already_card = $this->m_card->where(array("number"=>array('in',$card_number_list)))->select();
            }else{
                $start_card_number = I("post.start_card_number");
                $end_card_number = I("post.end_card_number");

                $already_card = $this->m_card->where("number >= '%s' and number <= '%s'",$start_card_number,$end_card_number)->select();
            }

            $msg_list = array();
            $add_number = 0;
            $log_card_lids = array();

            foreach ($already_card as $_key => $_card) {
                if(!empty($_card)){
                    $log_card_lids[$_card['lid']]++;

                    $_card['lid'] = $lid;

                    $this->m_card->save($_card);
                    $msg_list[] = array('status'=>'success','msg'=>"卡号:".$_card['number']."已分配到 ".$logistics['logistics_name']);
                    $add_number++;
                }else{
                    $msg_list[] = array('status'=>'error','msg'=>"卡号:".$card_num."不存在");
                }
            }

            foreach ($log_card_lids as $_lid => $_dec_number) {
                M("Logistics")->where(array("id" => $_lid))->setDec("total_card_num", $_dec_number);
            }

            M("Logistics")->where(array("id" => $lid))->setInc("total_card_num", $add_number);
            $this->assign("msg_list", $msg_list);
            $this->display("AdminCard/send_success");exit;
        }

        /**
         * 发卡提交
         */
        public function send_sub_post(){

            $lid = I("post.lid");
            $logistics = $this->m_logistics->where(array("id"=>$lid))->find();
            if(empty($logistics)){
                $this->error("物流公司不存在！");
            }

            $plid = get_logistics_id();
            $twhere = array("manager_id"=>$plid);
            $child_ids = $this->m_logistics->where($twhere)->getField('id');
            $child_ids = explode(',', $child_ids);
            $child_ids[] = $plid;

            $card_number = I("post.card_number");
            $number = I("post.number");
            if ($number > 200) {
                $this->error("每次发卡数量不得超过200张！");
            }
            $error_list = array();
            $add_number = 0;
            for($i = $card_number;$i<($card_number+$number);$i++){
                $card_num = sprintf("%010d",$i);
                $already_card = $this->m_card->where(array("number"=>$card_num))->find();
                if(in_array($already_card['lid'], $child_ids)){
                    $already_card['lid'] = $lid;

                    $this->m_card->save($already_card);
                    $add_number++;
                }else{
                    $error_list[] = "卡号:".$card_num."不属于本物流公司。";
                }

            }

            M("Logistics")->where(array("id"=>$lid))->save(array("total_card_num"=>$logistics['total_card_num']+$add_number));
            $this->assign("error_list", $error_list);
            $this->display("AdminCard/send_success");exit;
        }

        /**
         * 发卡提交
         */
        public function send_vip_sub_post(){

            $lid = I("post.lid");
            $logistics = $this->m_logistics->where(array("id"=>$lid))->find();
            if(empty($logistics)){
                $this->error("物流公司不存在！");
            }

            $plid = 1;
            $twhere = array("manager_id"=>$plid);
            $child_ids = $this->m_logistics->where($twhere)->getField('id');
            $child_ids = explode(',', $child_ids);
            $child_ids[] = $plid;

            $card_number = I("post.card_number");
            $number = I("post.number");
            if ($number > 200) {
                $this->error("每次发卡数量不得超过200张！");
            }
            $error_list = array();
            $add_number = 0;
            for($i = $card_number;$i<($card_number+$number);$i++){
                $card_num = sprintf("%010d",$i);
                $already_card = $this->m_card->where(array("number"=>$card_num))->find();
                if(in_array($already_card['lid'], $child_ids)){
                    $already_card['lid'] = $lid;
                    $this->m_card->save($already_card);
                    $add_number++;
                }elseif(empty($already_card)){
                    $insert = array(
                        'lid'=>$lid,
                        'number'=>$card_num,
                        'create_time'=>time(),
                    );
                    $this->m_card->add($insert);
                    $add_number++;
                }else{
                    $error_list[] = "卡号:".$card_num."不属于本物流公司。";
                }

            }

            M("Logistics")->where(array("id"=>$lid))->save(array("total_card_num"=>$logistics['total_card_num']+$add_number));
            $this->assign("error_list", $error_list);
            $this->display("AdminCard/send_success");exit;
        }

        /**
         * 发卡提交
         */
        public function send_post(){

            $lid = I("post.lid");
            $logistics = $this->m_logistics->where(array("id"=>$lid))->find();
            if(empty($logistics)){
                $this->error("物流公司不存在！");
            }

            $card_number = I("post.card_number");
            $number = I("post.number");
            if ($number > 200) {
                $this->error("每次发卡数量不得超过200张！");
            }
            $error_list = array();
            $add_number = 0;
            for($i = $card_number;$i<($card_number+$number);$i++){
                $card_num = sprintf("%010d",$i);
                $already_card = $this->m_card->where(array("number"=>$card_num))->find();
                if(!empty($already_card)){
                    $error_list[] = "卡号:".$card_num."已分配过物流公司。";
                }else{
                    $insert = array(
                        'lid'=>$lid,
                        'number'=>$card_num,
                        'create_time'=>time(),
                    );
                    $this->m_card->add($insert);
                    $add_number++;
                }

            }

            M("Logistics")->where(array("id"=>$lid))->save(array("total_card_num"=>$logistics['total_card_num']+$add_number));
            $this->assign("error_list", $error_list);
            $this->display("AdminCard/send_success");exit;
        }



        // 删除
        public function delete(){
            if(isset($_GET['id'])){
                $id = I("get.id",0,'intval');
                if ($this->m_card->where(array('id'=>$id))->delete() !==false) {
                    $this->success("删除成功！");
                } else {
                    $this->error("删除失败！");
                }
            }else{
                $this->error("参数有误！");
            }

        }

        /**
         * 状态操作
         */
        public function status(){
            $id = I("id");
            $status = I("status");
            $result = $this->m_card->opt_status($id,$status);
            if($result){
                $this->success("操作成功！");
            }else{
                $this->error("操作失败！");
            }
        }

    }